package mindmap.operation;

import mindmap.components.node.node;
import mindmap.controller.layoutController;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

/**
 * 撤销和恢复操作
 */
public class redoundo {
    public static Stack<node> undoStack = new Stack<>();//用于撤销
    public static Stack<node> redoStack = new Stack<>();//用于恢复
    public static String[] oper = new String[100];
    public static int opr = 0;
    public static List<node> children = new ArrayList<>();

    public static void operation(node n,String operType){
        opr++;
        oper[opr] = operType;
        undoStack.push(n);
    }

    public static void undo(){
        if(opr > 0) {
            node n = undoStack.pop();
            if (oper[opr].equals("add")) {
                if(n.root.arrangement.equals("bilateral")){
                    n.deleteBothNode();
                }else {
                    n.deleteNode();
                }
            }
            if(oper[opr].equals("delete")){
                children.add(n);
                re(n);
                rt();
            }
            opr--;
            redoStack.push(n);
        }
    }

    public static void redo(){
        opr++;
        if(oper[opr]!=null){
            node n = redoStack.pop();
            if(oper[opr].equals("add")){
                children.add(n);
                re(n);
                rt();
            }else {
                if(n.root.arrangement.equals("bilateral")){
                    n.deleteBothNode();
                }else {
                    n.deleteNode();
                }
            }
            undoStack.push(n);
        }else {
            opr--;
        }
    }

    public static void stackClean(){
        for (int i = opr+1; i < 100; i++){
            oper[i] = null;
            redoStack.clear();
        }
    }

    public static void re(node n){
        if(!n.getChildrenNode().isEmpty()) {
            for (node t : n.getChildrenNode()) {
                children.add(t);
                System.out.println("4");
                re(t);
            }
        }
    }
    public static void rt(){
        for(node n : children){
            n.getParentNode().getChildrenNode().remove(n);
        }
        for (node n : children){
            n.getParentNode().addChrNode(n);
            layoutController.getInstance().group1.getChildren().add(n);
            System.out.println(n.getLayoutX());
            System.out.println(n.getLayoutY());
            layoutController.getInstance().group2.getChildren().add(n.getLine());
        }
        children.clear();
    }

    public static void cleanAll(){
        for(int i = 0; i < 100; i++){
            oper[i] = null;
        }
        opr = 0;
        undoStack.clear();
        redoStack.clear();
    }

}
